package cn.qyd.leecode;

import java.util.List;

/**
 * @author 邱运铎
 * @date 2024-04-14 19:48
 */
public class TwoNumAddListNode {
    static class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

    public static void main(String[] args) {
        ListNode node3 = new ListNode(3);
        ListNode node2 = new ListNode(4, node3);
        ListNode node1 = new ListNode(2,node2);
        ListNode node31 = new ListNode(4);
        ListNode node21 = new ListNode(6, node31);
        ListNode node11 = new ListNode(5,node21);
        printNode(node1);
        printNode(node11);
        ListNode newNode1 = reverse(node1);
        ListNode newNode2 = reverse(node11);
        printNode(newNode1);
        printNode(newNode2);

        int temp = newNode1.val +newNode2.val;
        int carry = temp / 10;
        int remainder = temp % 10;
        ListNode result =new ListNode(remainder);
        ListNode node = result;

        while (newNode1.next != null || newNode2.next != null) {
            System.out.println(remainder);
            temp = 0;
            if (newNode1.next != null) {
                newNode1 = newNode1.next;
                temp += newNode1.val;
            }
            if (newNode2.next != null) {
                newNode2 = newNode2.next;
                temp += newNode2.val;
            }
            temp += carry;
            carry = temp / 10;
            remainder = temp % 10;
            System.out.println(temp);
            System.out.println(carry);
            System.out.println(remainder);
            node.next = new ListNode(remainder);
            node = node.next;
        }
        if (carry == 1) {
            node.next = new ListNode(1);
        }
        while (result.val == 0 && result.next != null) {
            result = result.next;
        }

        printNode(result);


    }

    public static ListNode reverse(ListNode list) {
        ListNode newList = new ListNode(list.val);
        while (list.next != null) {
            list = list.next;
            ListNode pre = new ListNode(list.val, newList);
            newList = pre;

        }
        return newList;
    }

    public static void printNode(ListNode node) {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }
}
